package nsqp

import (
	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
	"bgs/conf"
	"bgs/db"
	"bgs/grpc/imp/enums"
	handlers "bgs/nsqp/handlers/compensation"
	"bgs/nsqp/topic"
	"bgs/nsqp/util"
)

// CompensationProxy proxy compensation nsq message
type CompensationProxy struct {
	slog *zap.SugaredLogger
	subs []*nsq.Consumer
}

// NewCompensationProxy initialization
func NewCompensationProxy(
	nsqConf conf.NsqSection,
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
	failover *util.NsqFailover,
) (proxy *CompensationProxy, err error) {
	proxy = &CompensationProxy{
		slog: slog,
	}
	config := nsq.NewConfig()

	// closeUnpayExpiredOrderConsumer
	closeUnpayExpiredOrderConsumerTopic := topic.Make(enums.AppIDBGAPI)(topic.CloseUnpayExpiredOrder)
	closeUnpayExpiredOrderConsumer, err := nsq.NewConsumer(closeUnpayExpiredOrderConsumerTopic, appID, config)
	if err != nil {
		return
	}
	closeUnpayExpiredOrderConsumer.SetLogger(nsqLogger, nsq.LogLevelError)
	closeUnpayExpiredOrderConsumer.AddHandler(handlers.NewCloseUnpayExpiredOrderHandler(pgdao, slog))
	err = closeUnpayExpiredOrderConsumer.ConnectToNSQLookupd(nsqConf.NsqLookupds[0])
	if err != nil {
		return
	}
	proxy.subs = append(proxy.subs, closeUnpayExpiredOrderConsumer)

	// closeEndedActivityConsumer
	closeEndedActivityConsumerTopic := topic.Make(enums.AppIDBGAPI)(topic.CloseEndedActivity)
	closeEndedActivityConsumer, err := nsq.NewConsumer(closeEndedActivityConsumerTopic, appID, config)
	if err != nil {
		return
	}
	closeEndedActivityConsumer.SetLogger(nsqLogger, nsq.LogLevelError)
	closeEndedActivityConsumer.AddHandler(handlers.NewCloseEndedActivityHandler(pgdao, slog))
	err = closeEndedActivityConsumer.ConnectToNSQLookupd(nsqConf.NsqLookupds[0])
	if err != nil {
		return
	}
	proxy.subs = append(proxy.subs, closeEndedActivityConsumer)

	// Gracefully stop the consumer.
	// consumer.Stop()

	return
}
